<?php

include_once(APP_URL.'protected/lib/private/Check.php');
include_once(APP_URL.'protected/lib/qiniu/QManager.php');
require_once(APP_URL.'protected/config/GlobVar.php');
include_once(APP_URL.'protected/lib/private/File.php');
include_once(APP_URL.'protected/lib/private/Str.php');
include_once(APP_URL.'protected/lib/private/UtilPath.php');

class ItemController extends BaseController {

    public function init() {

        $arr = array(
            'item/addImage'
        );
        $url = Yii::app()->urlManager->parseUrl(Yii::app()->request);
        if(!Str::strContainArray($url, $arr)) {
            if(!$this->session()) {
                $this->redirect(URL_USER_LOGIN);
                exit;
            }
            $this->layout = '//layouts/layout_developer';
        }
    }

    public function actionList() {
        // http://192.168.3.69/item/list

        $projectId = Check::checkGetParam(0, 'projectId', false);

        $userId = Yii::app()->session['userId'];
        $condArr = array(
            'select' => array('name', 'path_url'),
            'condition' => 'id=:projectId AND user_id=:userId',
            'params' => array('projectId' => $projectId, 'userId' => $userId)
        );
        $TblProject = new TblProject();
        $result = $TblProject->selectRecord($condArr);
        if(!$result) {
            echo Resp::retFail(0, 'find roam failed');
            exit;
        }
        $projectName = $result->name;
        $projectLink = null;
        if($result->path_url) {
            $projectLink = URL_PAINTER_BROWSER.'/projectId/'.$projectId;
        }

        $condArr = array(
            'select' => array('*'),
            'order' => 'id DESC',
            'condition' => 'project_id=:projectId',
            'params' => array('projectId' => $projectId)
        );
        $TblProjectFile = new TblProjectFile();
        $result = $TblProjectFile->selectRecordAll($condArr);
        $projectDataName = null;
        $projectDataTime = null;
        $dataFileId = null;
        $projectImageList = [];
        $projectLogoName = null;
        $projectLogoUrl = null;
        $projectLogoTime = null;
        $logoFileId = null;
        $projectMusicName = null;
        $projectMusicTime = null;
        $projectMusicUrl = null;
        $musicFileId = null;
        if($result) {
            foreach ($result as $value) {
                if($value->type == 1) {
                    $projectDataName = $value->name;
                    $projectDataTime = $value->time;
                    $dataFileId = $value->id;
                } else if($value->type == 2) {
                    $projectImageList[] = $value;
                } else if($value->type == 3) {
                    $projectLogoName = $value->name;
                    $projectLogoUrl = $value->url;
                    $projectLogoTime = $value->time;
                    $logoFileId = $value->id;
                } else if($value->type == 4) {
                    $projectMusicName = $value->name;
                    $projectMusicTime = $value->time;
                    $projectMusicUrl = $value->url;
                    $musicFileId = $value->id;
                }
            }
        }

        $policy = array(
            'callbackUrl' => URL_SERVER.'item/addImage',
            'callbackBody' => '{
                "projectId" : '.$projectId.',
                "fKey" : "$(key)",
                "fHash" : "$(hash)",
                "fName" : "$(fname)",
                "fSize" : "$(x:fSize)"
                }'
        );
//        $key = Qiniu\base64_urlSafeEncode('demo'.$projectId.microtime());
//        echo $key;exit;
        $manager = new QManager('demo', $policy, null);
        $token = $manager->getToken();
        $domain = 'http://ohwws5hrj.bkt.clouddn.com/';
        $arr = array(
            'projectId' => $projectId,
            'projectName' => $projectName,
            'projectLink' => $projectLink,
            'projectDataName' => $projectDataName,
            'projectDataTime' => $projectDataTime,
            'dataFileId' => $dataFileId,
            'projectImageList' => $projectImageList,
            'projectLogoName' => $projectLogoName,
            'projectLogoUrl' => $projectLogoUrl,
            'projectLogoTime' => $projectLogoTime,
            'logoFileId' => $logoFileId,
            'projectMusicName' => $projectMusicName,
            'projectMusicTime' => $projectMusicTime,
            'projectMusicUrl' => $projectMusicUrl,
            'musicFileId' => $musicFileId,
            'token' => $token,
            'domain' => $domain
        );

        $this->render('list', $arr);
    }

    public function actionAddData() {
        // http://192.168.3.69/project/addData

        $projectId = Check::checkPostParam(0, 'projectId', false);

        if($_FILES["file"]["error"] > 0) {
            echo Resp::retFail(0, 'file error');
            exit;
        }
        $fileName = $_FILES["file"]["name"];
        $fileSize = $_FILES["file"]["size"];
        $fileType = $_FILES["file"]["type"];
        $fileExtension = pathinfo($fileName);
        $fileExtension = $fileExtension['extension'];
        if($fileName != 'm.data') {
            echo Resp::retFail(0, 'file name error');
            exit;
        }
        if($fileExtension != 'data') {
            echo Resp::retFail(0, 'file extension error');
            exit;
        }
        if($fileSize > 10485760) {//10MB
            echo Resp::retFail(0, 'file size error');
            exit;
        }
        if($fileType != 'application/octet-stream') {
            echo Resp::retFail(0, 'file type error');
            exit;
        }

        $condArr = array(
            'select' => array('*'),
            'condition' => 'project_id=:projectId AND type=:type',
            'params' => array('projectId' => $projectId, 'type' => 1)
        );
        $TblProjectFile = new TblProjectFile();
        $result = $TblProjectFile->selectRecord($condArr);
        if($result) {
            $fileUrl = $result->url;
            $ret = move_uploaded_file($_FILES["file"]["tmp_name"], $fileUrl);
            if(!$ret) {
                echo Resp::retFail(0, 'file error');
                exit;
            }

            $condArr = array(
                'condition' => 'project_id=:projectId AND type=:type',
                'params' => array('projectId' => $projectId, 'type' => 1)
            );
            $contArr = array(
                'time' => time()
            );
            if(!$TblProjectFile->updateRecord($condArr, $contArr)) {
                echo Resp::retFail(0, 'server error !');
                exit;
            }

            echo Resp::retSuc(1, (object)array());
        } else {
            $dir = PATH_FILE_ROOT.$projectId.'/';
            $file = md5($projectId.time()).'.data';
            if(!is_dir($dir)) {
                mkdir($dir, 0755);
            }
            $fileUrl = $dir.$file;

            $ret = move_uploaded_file($_FILES["file"]["tmp_name"], $fileUrl);
            if(!$ret) {
                echo Resp::retFail(0, 'file error');
                exit;
            }
            $contArr = array(
                'project_id' => $projectId,
                'name' => $fileName,
                'url' => $fileUrl,
                'size' => $fileSize,
                'time' => time(),
                'type' => 1
            );
            if(!$TblProjectFile->addRecord('project_file', $contArr)) {// if not exist just add db
                echo Resp::retFail(0, 'server error !');
                exit;
            }

            echo Resp::retSuc(1, (object)array());
        }
    }

    public function actionAddImage() {
        // http://115.28.164.217/item/addImage

        $body = file_get_contents('php://input');
        if(!$body) {
            echo Resp::retFail(0, 'input is null');
            exit;
        }
        $result = json_decode($body);
        if(!is_object($result) || empty($result)) {
            echo Resp::retFail(0, 'input decode null');
            exit;
        }

        $projectId = $result->projectId;
        $fileKey = $result->fKey;
//        $fileHash = $result->fHash;
        $fileName = $result->fName;
        $fileSize = $result->fSize;
        $domain = 'http://ohwws5hrj.bkt.clouddn.com/';
        $fileUrl = $domain.$fileKey;

        $fileExtension = pathinfo($fileName);
        $fileExtension = $fileExtension['extension'];
        if($fileExtension != 'jpg' && $fileExtension != 'JPG') {
            echo Resp::retFail(0, $fileExtension.' file extension error');
            exit;
        }
        if($fileSize > 10485760) {//10MB
            echo Resp::retFail(0, 'file size error');
            exit;
        }

        $condArr = array(
            'select' => array('*'),
            'condition' => 'project_id=:projectId AND name=:name AND type=:type',
            'params' => array('projectId' => $projectId, 'name' => $fileName, 'type' => 2)
        );
        $TblProjectFile = new TblProjectFile();
        $result = $TblProjectFile->selectRecord($condArr);
        if($result) {// file exist just update file url key

            $condArr = array(
                'condition' => 'project_id=:projectId AND name=:name AND type=:type',
                'params' => array('projectId' => $projectId, 'name' => $fileName, 'type' => 2)
            );
            $contArr = array(
                'url' => $fileUrl,
                'time' => time()
            );
            if(!$TblProjectFile->updateRecord($condArr, $contArr)) {
                echo Resp::retFail(0, 'server error !');
                exit;
            }

            echo Resp::retSuc(1, (object)array());
        } else {

            $contArr = array(
                'project_id' => $projectId,
                'name' => $fileName,
                'url' => $fileUrl,
                'size' => $fileSize,
                'time' => time(),
                'type' => 2
            );
            if(!$TblProjectFile->addRecord('project_file', $contArr)) {// if not exist just add db
                echo Resp::retFail(0, 'server error !');
                exit;
            }

            echo Resp::retSuc(1, (object)array());
        }

    }

    public function actionAddLogo() {
        // http://192.168.3.69/project/addLogo

        $projectId = Check::checkPostParam(0, 'projectId', false);

        if($_FILES["file"]["error"] > 0) {
            echo Resp::retFail(0, 'file error');
            exit;
        }
        $fileName = $_FILES["file"]["name"];
        $fileSize = $_FILES["file"]["size"];
        $fileType = $_FILES["file"]["type"];
        $fileExtension = pathinfo($fileName);
        $fileExtension = $fileExtension['extension'];
        if($fileExtension != 'jpg' && $fileExtension != 'png') {
            echo Resp::retFail(0, 'file extension error');
            exit;
        }
        if($fileSize > 2097152) {//2MB
            echo Resp::retFail(0, 'file size error');
            exit;
        }
        if($fileType != 'image/jpeg' && $fileType != 'image/png') {
            echo Resp::retFail(0, 'file type error');
            exit;
        }

        $condArr = array(
            'select' => array('*'),
            'condition' => 'project_id=:projectId AND type=:type',
            'params' => array('projectId' => $projectId, 'type' => 3)
        );
        $TblProjectFile = new TblProjectFile();
        $result = $TblProjectFile->selectRecord($condArr);
        if($result) {
            $fileUrl = $result->url;
            $ret = move_uploaded_file($_FILES["file"]["tmp_name"], $fileUrl);
            if(!$ret) {
                echo Resp::retFail(0, 'file error');
                exit;
            }

            $condArr = array(
                'condition' => 'project_id=:projectId AND type=:type',
                'params' => array('projectId' => $projectId, 'type' => 3)
            );
            $contArr = array(
                'name' => $fileName,
                'time' => time()
            );
            if(!$TblProjectFile->updateRecord($condArr, $contArr)) {
                echo Resp::retFail(0, 'server error !');
                exit;
            }

            echo Resp::retSuc(1, (object)array());
        } else {
            $dir = PATH_FILE_ROOT.$projectId.'/';
            $file = md5($projectId.time()).'.jpg';
            if(!is_dir($dir)) {
                mkdir($dir, 0755);
            }
            $fileUrl = $dir.$file;

            $ret = move_uploaded_file($_FILES["file"]["tmp_name"], $fileUrl);
            if(!$ret) {
                echo Resp::retFail(0, 'file error');
                exit;
            }
            $contArr = array(
                'project_id' => $projectId,
                'name' => $fileName,
                'url' => $fileUrl,
                'size' => $fileSize,
                'time' => time(),
                'type' => 3
            );
            if(!$TblProjectFile->addRecord('project_file', $contArr)) {// if not exist just add db
                echo Resp::retFail(0, 'server error !');
                exit;
            }

            echo Resp::retSuc(1, (object)array());
        }
    }

    public function actionAddMusic() {
        // http://192.168.3.69/project/addMusic

        $projectId = Check::checkPostParam(0, 'projectId', false);

        if($_FILES["file"]["error"] > 0) {
            echo Resp::retFail(0, 'file error');
            exit;
        }
        $fileName = $_FILES["file"]["name"];
        $fileSize = $_FILES["file"]["size"];
        $fileType = $_FILES["file"]["type"];
        $fileExtension = pathinfo($fileName);
        $fileExtension = $fileExtension['extension'];
        if($fileExtension != 'mp3') {
            echo Resp::retFail(0, 'file extension error');
            exit;
        }
        if($fileSize > 10485760) {//10MB
            echo Resp::retFail(0, 'file size error');
            exit;
        }
        if($fileType != 'audio/mp3') {
            echo Resp::retFail(0, 'file type error');
            exit;
        }

        $condArr = array(
            'select' => array('*'),
            'condition' => 'project_id=:projectId AND type=:type',
            'params' => array('projectId' => $projectId, 'type' => 4)
        );
        $TblProjectFile = new TblProjectFile();
        $result = $TblProjectFile->selectRecord($condArr);
        if($result) {
            $fileUrl = $result->url;
            $ret = move_uploaded_file($_FILES["file"]["tmp_name"], $fileUrl);
            if(!$ret) {
                echo Resp::retFail(0, 'file error');
                exit;
            }

            $condArr = array(
                'condition' => 'project_id=:projectId AND type=:type',
                'params' => array('projectId' => $projectId, 'type' => 4)
            );
            $contArr = array(
                'name' => $fileName,
                'time' => time()
            );
            if(!$TblProjectFile->updateRecord($condArr, $contArr)) {
                echo Resp::retFail(0, 'server error !');
                exit;
            }

            echo Resp::retSuc(1, (object)array());
        } else {
            $dir = PATH_FILE_ROOT.$projectId.'/';
            $file = md5($projectId.time()).'.mp3';
            if(!is_dir($dir)) {
                mkdir($dir, 0755);
            }
            $fileUrl = $dir.$file;

            $ret = move_uploaded_file($_FILES["file"]["tmp_name"], $fileUrl);
            if(!$ret) {
                echo Resp::retFail(0, 'file error');
                exit;
            }
            $contArr = array(
                'project_id' => $projectId,
                'name' => $fileName,
                'url' => $fileUrl,
                'size' => $fileSize,
                'time' => time(),
                'type' => 4
            );
            if(!$TblProjectFile->addRecord('project_file', $contArr)) {// if not exist just add db
                echo Resp::retFail(0, 'server error !');
                exit;
            }

            echo Resp::retSuc(1, (object)array());
        }
    }

    public function actionDelete() {
        // http://192.168.3.69/item/delete

        $projectId = Check::checkGetParam(0, 'projectId', false);
        $fileId = Check::checkGetParam(0, 'fileId', false);

        $TblProjectFile = new TblProjectFile();
        $TblProject = new TblProject();

        // get file name of cloud to delete it then
        $condArr = array(
            'select' => array('url','type'),
            'condition' => 'id=:fileId',
            'params' => array('fileId' => $fileId)
        );
        $result = $TblProjectFile->selectRecord($condArr);
        $fileNameCloud = null;
        $type = null;
        if($result) {
            $fileNameCloud = basename($result->url);
            $type = $result->type;
        }

        // delete file record
        $condArr = array(
            'condition' => 'id=:fileId',
            'params' => array('fileId' => $fileId)
        );
        if(!$TblProjectFile->deleteRecord($condArr)) {
            echo Resp::retFail(0, 'delete project file failed');
            exit;
        }

        if($type == 1) {
            $condArr = array(
                'condition' => 'id=:projectId',
                'params' => array('projectId' => $projectId)
            );
            $contArr = array(
                'map_url' => '',
                'prj_url' => '',
                'path_url' => ''
            );
            if(!$TblProject->updateRecord($condArr, $contArr)) {
                echo Resp::retFail(0, 'update failed');
                exit;
            }
        } else if($type == 2) {
            // delete it from cloud
            $manager = new QManager('demo', null, null);
            $manager->deleteFile($fileNameCloud);

            $condArr = array(
                'select' => array('name','url'),
                'order' => 'id DESC',
                'condition' => 'project_id=:projectId AND type=:type',
                'params' => array('projectId' => $projectId, 'type' => 2)
            );
            $result = $TblProjectFile->selectRecordAll($condArr);
            if(!$result) {
                $condArr = array(
                    'condition' => 'id=:projectId',
                    'params' => array('projectId' => $projectId)
                );
                $contArr = array(
                    'path_url' => ''
                );
                $TblProject->updateRecord($condArr, $contArr);
            }
        }

        $this->redirect(URL_ITEM_LIST.'/projectId/'.$projectId);
    }

    public function actionLink() {
        // http://192.168.3.69/item/link

        $projectId = Check::checkGetParam(0, 'projectId', false);

        $TblProject = new TblProject();
        $TblProjectFile = new TblProjectFile();

        // check exist map & prj file
        $condArr = array(
            'select' => array('*'),
            'condition' => 'project_id=:projectId AND type=:type',
            'params' => array('projectId' => $projectId, 'type' => 1)
        );
        $resultFile = $TblProjectFile->selectRecord($condArr);
        if(!$resultFile) {
            echo Resp::retFail(0, 'find data file failed');
            exit;
        }
        $dataUrl = $resultFile->url;
        if(!is_file($dataUrl)) {
            echo Resp::retFail(0, 'data file not exist');
            exit;
        }
        $dataStream = file_get_contents($dataUrl);
        if(!$dataStream) {
            echo Resp::retFail(0, 'read data file failed');
            exit;
        }

        $userId = Yii::app()->session['userId'];
        $condArr = array(
            'select' => array('*'),
            'condition' => 'id=:projectId AND user_id=:userId',
            'params' => array('projectId' => $projectId, 'userId' => $userId)
        );
        $resultProject = $TblProject->selectRecord($condArr);
        if(!$resultProject) {
            echo Resp::retFail(0, 'find project failed');
            exit;
        }
        $projectName = $resultProject->name;
        $mapUrl = $resultProject->map_url;
        $prjUrl = $resultProject->prj_url;
        if($mapUrl && $prjUrl) {
            $arr = array(
                'projectId' => $projectId,
                'mapUrl' => $mapUrl,
                'prjUrl' => '/item/getPrj/projectId/'.$projectId,
                'projectName' => $projectName
            );
            $this->render('link', $arr);
            exit;
        }
//
        $pathInfo = pathinfo($dataUrl);
        $file = $pathInfo['basename'];
        $fileName = explode(".", $file)[0];
        $dir = $pathInfo['dirname'];
        exec('chmod 755 '.$dir);
        chdir($dir);
//        echo $fileName;exit;

        // aes decrypt
        $AesVersion = File::readFileLastLines($dataUrl, 1);
        $AesVersion = substr($AesVersion, -8);
        if(!array_key_exists($AesVersion, GlobVar::$AES_KEY_ARRAY)) {
            echo Resp::retFail(0, 'data file error');
            exit;
        }
        $AesKey = GlobVar::$AES_KEY_ARRAY[$AesVersion];
        if(!array_key_exists($AesVersion, GlobVar::$AES_IV_ARRAY)) {
            echo Resp::retFail(0, 'data file error');
            exit;
        }
        $AesIV = GlobVar::$AES_IV_ARRAY[$AesVersion];
//        echo $AesKey,$AesIV;exit;
        $fileCopy = $file.'.cp';
        $cmd = 'cp -f '.$file.' '.$fileCopy.' && sed -i \'s/;00000001//\' '.$fileCopy;
        exec($cmd);
        $fileZip = $fileName.'.zip';
        $cmd = 'openssl enc -aes-128-cbc -d -in '.$fileCopy.' -out '.$fileZip.' -K '.$AesKey.' -iv '.$AesIV;
        exec($cmd);

        // zip decrypt
        $zipVersion = File::readFileLastLines($fileZip, 1);
        $zipVersion = substr($zipVersion, -8);
        if(!array_key_exists($zipVersion, GlobVar::$ZIP_ARRAY)) {
            echo Resp::retFail(0, 'data file error');
            exit;
        }
        $zipPassword = GlobVar::$ZIP_ARRAY[$zipVersion];
//        echo $zipPassword;exit;
        $cmd = 'sed -i \'s/;00000001//\' '.$fileZip;
        exec($cmd);
        $cmd = 'unzip -P '.$zipPassword.' -o '.$fileZip;
        exec($cmd);

        // convert map to image
        $fileMap = $fileName.'.m.png';
        $cmd = 'convert m.pgm '.$fileMap;
        exec($cmd);
        $size = getimagesize($dir.'/'.$fileMap);
        $mapWidth = $size['0'];
        $mapHeight = $size['1'];

        // image process with OpenCV
        $cmd = 'util-image '.$fileMap.' '.$fileMap.' FFFFFF 000000 BABABA';
        $ret = exec($cmd);
        if(!$ret) {
            echo Resp::retFail(0, 'map process failed');
            exit;
        }
        $retObj = json_decode($ret);
        if(!$retObj) {
            echo Resp::retFail(0, 'map process failed');
            exit;
        }
        if($retObj->retCode != 1) {
            echo Resp::retFail(0, 'map process failed');
            exit;
        }

        // generate project file
        $prjStr = file_get_contents('m.prj');
        $prjArr = explode(";", $prjStr);
        $versionPrj = $prjArr[0];
        $contentPrj = $prjArr[1];
        $yamlStr = file_get_contents('m.yaml');
        $resolution = explode(":", Str::trim(Str::getLine($yamlStr, 1)))[1];
        $origin = explode(":", Str::trim(Str::getLine($yamlStr, 2)))[1];
        $originArr = explode(",", rtrim(ltrim($origin, '['), ']'));
        $originX = $originArr[0];
        $originY = $originArr[1];
        $prjJsonObj = json_decode(substr($contentPrj, 0, strlen($contentPrj) - 1).']');
        // crypt project file
        $prjArr = [];
        foreach($prjJsonObj as $key => $value) {
            $prjArr[] = array($value->image, $value->x * 2, $value->y * 3, $value->yaw, $value->path, $key);
        }
        $prjStr = json_encode(array(intval($versionPrj) * 10, floatval($resolution) * 2, floatval($originX) * 3, floatval($originY) * 4,
            $mapWidth * 2, $mapHeight * 3, array(0, $prjArr)));
//        echo $prjStr;exit;

        $filePrj = md5($projectId.microtime()).'.m.prj';
        if(!file_put_contents($filePrj, $prjStr)) {
            echo Resp::retFail(0, 'deal data file error');
            exit;
        }

        // save map & prj info to db
        $mapUrl = URL_FILE_ROOT.$projectId.'/'.$fileMap;
        $prjUrl = PATH_FILE_ROOT.$projectId.'/'.$filePrj;

        $condArr = array(
            'select' => array('prj_url'),
            'condition' => 'id=:projectId',
            'params' => array('projectId' => $projectId)
        );
        $result = $TblProject->selectRecord($condArr);
        if($result) {
            $prjUrlOld = $result->prj_url;
            $cmd = 'rm -rf '.$prjUrlOld;
            exec($cmd);
        }

        $condArr = array(
            'condition' => 'id=:projectId',
            'params' => array('projectId' => $projectId)
        );
        $contArr = array(
            'map_url' => $mapUrl,
            'prj_url' => $prjUrl
        );
        if(!$TblProject->updateRecord($condArr, $contArr)) {
            echo Resp::retFail(0, 'server error !');
            exit;
        }

        // remove tmp files
        $cmd = 'rm -rf '.$fileCopy.' '.$fileZip.' m.prj m.pb m.yaml m.pgm ';
        exec($cmd);

        chdir(APP_URL);
//        echo $mapUrl,$prjUrl;exit;

        $userId = Yii::app()->session['userId'];
        $condArr = array(
            'select' => array('name'),
            'condition' => 'id=:projectId AND user_id=:userId',
            'params' => array('projectId' => $projectId, 'userId' => $userId)
        );
        $TblProject = new TblProject();
        $result = $TblProject->selectRecord($condArr);
        if(!$result) {
            echo Resp::retFail(0, 'find project failed');
            exit;
        }
        $projectName = $result->name;

        $arr = array(
            'projectId' => $projectId,
            'mapUrl' => $mapUrl,
            'prjUrl' => '/item/getPrj/projectId/'.$projectId,
            'projectName' => $projectName
        );
        $this->render('link', $arr);
    }

    public function actionAutoPath() {
        // http://192.168.3.69/item/autoPath

        $projectId = Check::checkPostParam(0, 'projectId', false);

        $TblProject = new TblProject();

        $userId = Yii::app()->session['userId'];
        $condArr = array(
            'select' => array('*'),
            'condition' => 'id=:projectId AND user_id=:userId',
            'params' => array('projectId' => $projectId, 'userId' => $userId)
        );
        $resultProject = $TblProject->selectRecord($condArr);
        if(!$resultProject) {
            echo Resp::retFail(0, 'find project failed');
            exit;
        }
        $mapUrl = $resultProject->map_url;
        $prjUrl = $resultProject->prj_url;
        if(!$mapUrl || !$prjUrl) {
            echo Resp::retFail(0, 'find project map or prj failed');
            exit;
        }

        $mapFile = '/alidata/www/maptopro/file/'.$projectId.'/'.basename($mapUrl);
        $prjFile = '/alidata/www/maptopro/file/'.$projectId.'/'.basename($prjUrl);
//        $prjSaveFile = '/alidata/www/maptopro/file/'.$projectId.'/auto_'.basename($prjUrl);
        $prjSaveFile = '/alidata/www/maptopro/file/'.$projectId.'/'.basename($prjUrl);

        // auto process with OpenCV
        $cmd = 'UtilPath '.$mapFile.' '.$prjFile.' '.$prjSaveFile;
        $ret = exec($cmd);
        if(!$ret) {
            echo Resp::retFail(0, 'path process failed 001');
            exit;
        }
        $retObj = json_decode($ret);
        if(!$retObj) {
            echo Resp::retFail(0, 'path process failed 002');
            exit;
        }
        if($retObj->retCode != 1) {
            echo Resp::retFail(0, 'path process failed 003');
            exit;
        }

        echo Resp::retSuc(1, (object)array());
    }

    public function actionGetPrj() {
        // http://192.168.3.69/item/getPrj

        $projectId = Check::checkGetParam(0, 'projectId', false);

        $userId = Yii::app()->session['userId'];
        $condArr = array(
            'select' => array('prj_url'),
            'condition' => 'id=:projectId AND user_id=:userId',
            'params' => array('projectId' => $projectId, 'userId' => $userId)
        );
        $TblProject = new TblProject();
        $result = $TblProject->selectRecord($condArr);
        if(!$result) {
            echo Resp::retFail(0, 'find project failed');
            exit;
        }
        $prjUrl = $result->prj_url;
//        echo $prjUrl;exit;

        $data = file_get_contents($prjUrl);
        if(!$data) {
            echo Resp::retFail(0, 'read prj file failed');
            exit;
        }
//        echo $data;exit;

        $dataObj = null;
        $dataObj = json_decode($data);
        if(!$dataObj) {
            echo Resp::retFail(0, 'decode prj file failed');
            exit;
        }
//        echo var_dump($dataObj);exit;
        $prjObj = $dataObj[6][1];
        $prjArr = [];
        foreach($prjObj as $value) {
            foreach($value[4] as $key=>$val) {
                $value[4][$key] = $val + Str::randomFloat();
            }
            $prjArr[] = array($value[1], $value[2], $value[4], Str::randomFloat());
        }

        $data = json_encode(array($dataObj[0], $dataObj[1], $dataObj[2], $dataObj[3],$dataObj[4], $dataObj[5], array($dataObj[6][0], $prjArr)));
        echo $data;
    }

    public function actionSavePath() {
        // http://192.168.3.69/item/savePath

        // parse path data
        $projectId = Check::checkPostParam(0, 'projectId', false);
        $pathData = Check::checkPostParam(0, 'data', false);
        $pathObj = json_decode($pathData);
        if(!$pathObj) {
            echo Resp::retFail(0, 'json decode path data failed');
            exit;
        }

        // get origin prj data
        $userId = Yii::app()->session['userId'];
        $condArr = array(
            'select' => array('*'),
            'condition' => 'id=:projectId AND user_id=:userId',
            'params' => array('projectId' => $projectId, 'userId' => $userId)
        );
        $TblProject = new TblProject();
        $result = $TblProject->selectRecord($condArr);
        if(!$result) {
            echo Resp::retFail(0, 'find project failed');
            exit;
        }
        $prjUrl = $result->prj_url;
        $pathUrl = $result->path_url;
        $prjData = file_get_contents($prjUrl);
        if(!$prjData) {
            echo Resp::retFail(0, 'read origin project failed');
            exit;
        }
        $prjObj = json_decode($prjData);
        if(!$prjObj) {
            echo Resp::retFail(0, 'json decode prj data failed');
            exit;
        }

        // merge new with origin
        $prjObj[6][0] = $pathObj[0];// set origin node id
        foreach($pathObj[1] as $key=>$value) {// set new path array
            $prjObj[6][1][$key][4] = $value[2];// path
        }
        $prjData = json_encode($prjObj);
        if(!file_put_contents($prjUrl, $prjData)) {// save origin
            echo Resp::retFail(0, 'save prj data failed');
            exit;
        }

        // generate browser path file
        $prjPathObj = &$prjObj[6][1];
        foreach($prjPathObj as $key=>$value) {
            $prjPathObj[$key][1] = $value[1] / 2;
            $prjPathObj[$key][2] = $value[2] / 3;

            $x = $prjPathObj[$key][1];
            $prjPathObj[$key][1] = -$prjPathObj[$key][2];
            $prjPathObj[$key][2] = $x;

        }
//        echo json_encode($prjObj[6]);exit;

        // convert to roam path
        $pathObj = UtilPath::convert($projectId, $prjObj[6]);// convert to roam path

        // save content to pth file
        $pathStr = str_replace('\\/', '/', json_encode($pathObj));
        if(!$pathUrl) {
            $pathUrl = PATH_FILE_ROOT.$projectId.'/'.md5($projectId.microtime()).'.m.path';
        }
        if(!file_put_contents($pathUrl, $pathStr)) {
            echo Resp::retFail(0, 'save path failed');
            exit;
        }

        // save info to db
        $condArr = array(
            'condition' => 'id=:projectId',
            'params' => array('projectId' => $projectId)
        );
        $contArr = array(
            'path_url' => $pathUrl
        );
        if(!$TblProject->updateRecord($condArr, $contArr)) {
            echo Resp::retFail(0, 'server error !');
            exit;
        }

        echo Resp::retSuc(1, (object)array());
    }

    public function actionPreviewPath() {
        // http://192.168.3.69/item/previewPath


    }

}
